<template>
    <div class="home-wrapper">
        <div class="filters-wrapper cust_wrap" v-loading.fullscreen.lock="fullscreenLoading">
            <el-tabs v-model="activeName">
                <el-tab-pane label="账号管理" name="first">
                    <el-row type="flex" align="middle" style="flex-wrap: wrap;margin-bottom: 5px;position: relative;">
                        <div class="form-wrapper" style="width: 300px;">
                            <el-input placeholder="请输入内容" size="small" v-model="account_search" class="input-with-select" @keyup.enter.native="loadAccountList({})">
                                <el-button slot="append" @click="loadAccountList({})" icon="el-icon-search"></el-button>
                            </el-input>
                        </div>
                        <div class="form-wrapper">
                            <span class="filter-label">筛选：</span>
                            <el-select v-model="config_search" @change="loadAccountList({})" placeholder="请选择" size="small" class="select-wrapper">
                                <el-option label="全部" value=""></el-option>
                                <el-option label="已分配" value="1"></el-option>
                                <el-option label="未分配" value="2"></el-option>
                            </el-select>
                        </div>
                        <div class="cus-but">
                            <el-button :disabled="!isAdmin" type="primary" @click="syncClick" :loading="syncloading" size="mini">同步账户</el-button>
                            <el-button style="margin-left: 10px;" @click="exportClick" size="mini">导出</el-button>
                        </div>
                    </el-row>
                    <el-table :data="accountlist" border
                        :header-cell-style="{'text-align':'center','background':'#f7f7f7','color':'#666'}"
                        style="width: 100%"  @selection-change="handleSelectionChange" ref="multipleTable">
                        <el-table-column type="selection" width="55" align="center">
                        </el-table-column>
                        <el-table-column prop="account" label="账户" align="center">
                        </el-table-column>
                        <el-table-column prop="project" label="项目" align="center">
                        </el-table-column>
                        <el-table-column prop="project_user" label="优化师" align="center">
                        </el-table-column>
                        <el-table-column prop="project_admin" label="负责人" align="center"></el-table-column>
                        <el-table-column prop="depart" label="部门" align="center"></el-table-column>
                        <el-table-column prop="status" label="状态" align="center"></el-table-column>
                        <el-table-column prop="caozuo" width="100px" label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button v-if="scope.row.is_update == 1" size="mini" type="danger" @click="showConfig(scope.row)">分配
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-dialog title="分配管理" :visible.sync="fenpei" width="30%" center :close-on-click-modal="false">
                        <el-row type="flex" align="middle" justify="center">
                            <el-form label-width="100px" :model="configform" ref="configform" :rules="configRules" style="width: 85%;">
                                <el-form-item label="账户：" prop="account">
                                    <el-input v-model="configform.account" size="small"
                                        style="width: 100%;" :disabled="true" />
                                </el-form-item>
                                <el-form-item class="is-required" label="项目：" prop="id_project">
                                    <el-select v-model="configform.id_project" filterable placeholder="选择项目" size="small"
                                        style="width: 100%;">
                                        <el-option v-for="item in projectlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                                <!-- <el-form-item class="is-required" label="负责人：">
                                    <el-select v-model="configform.id_project_admin" filterable placeholder="选择负责人" size="small"
                                        style="width: 100%;">
                                        <el-option v-for="item in userlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item class="is-required" label="所属部门：">
                                    <el-select v-model="configform.id_depart" filterable placeholder="选择部门" size="small"
                                        style="width: 100%;">
                                        <el-option v-for="item in departlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item> -->
                            </el-form>
                        </el-row>
                        <el-row type="flex" align="middle" justify="center">
                            <el-button size="small" @click="cancelConfig">取 消</el-button>
                            <el-button size="small" type="primary" @click="configPost">确认</el-button>
                        </el-row>
                    </el-dialog>
                    <el-row type="flex" justify="end" style="margin-top: 20px;">
                        <div class="form-wrapper" v-if="isAdmin" style="margin-right: 10px;">
                            <el-button size="small" @click="toggleSelection(accountlist)">全选</el-button>
                            <el-button size="small" @click="showConfig(null)" type="danger">分配</el-button>
                        </div>
                        <el-pagination background layout="prev, pager, next" :current-page.sync="curPageAccount" :total="accountTotal" :page-size="pageSize" @current-change="handleCurrentChange('account',$event)">
                        </el-pagination>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="代理商管理" name="second">
                    <div class="cus-but">
                        <el-button :disabled="!isAdmin" type="primary" size="mini" @click="authClick">授权</el-button>
                    </div>
                    <el-table :data="agentlist" border
                        :header-cell-style="{'text-align':'center','background':'#f7f7f7','color':'#666'}"
                        style="width: 100%">
                        <el-table-column prop="name" label="代理商" align="center">
                        </el-table-column>
                        <el-table-column prop="add_time" label="授权时间" align="center">
                        </el-table-column>
                        <el-table-column prop="update_time" label="到期时间" align="center">
                        </el-table-column>
                        <el-table-column prop="dueto_state" width="200" label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button v-if="isAdmin" size="mini" type="danger" @click="deleteAgent(scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>
<style>
    .cust_wrap .el-tabs__content {
        overflow: initial;
        position: relative;
    }

    .cust_wrap .el-tabs__nav-wrap::after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: #E4E7ED;
        z-index: 1;
    }

    .cust_wrap .input-with-select .el-input-group__prepend {
        background-color: #fff;
        color: #666;
    }

    .cust_wrap .el-tabs__content {
        overflow: initial;
        position: relative;
    }

    .cust_wrap .cus-but {
        position: absolute;
        right: 0;
        top: -53px;
    }
</style>
<script>
import { pageParams,ToutiaoAuthUrl,isAdmin } from '@/settings'
import { getToken } from '@/util/auth'
    export default {
        data() {
            // var validateId = (rule, value, callback) => {
            //     if (!value) {
            //     return callback(new Error('请选择项目'));
            //     }
            //     setTimeout(() => {
            //     if (!Number.isInteger(value)) {
            //         callback(new Error('请选择项目'));
            //     } else {
            //         if (value < 1) {
            //         callback(new Error('请选择项目'));
            //         } else {
            //         callback();
            //         }
            //     }
            //     }, 1000);
            // }
            return {
                fullscreenLoading: false,
                syncloading: false,
                pageSize: pageParams.pageSize,
                activeName: 'first',
                fenplist: '',
                config_search: '',
                account_search: '',
                fenpei: false,
                accountlist: [],
                accountTotal: 0,
                configform: {
                    id:[],
                    account: '',
                    id_project: '',
                    // id_depart: '',
                    // id_project_admin: '',
                },
                configRules: {
                    id_project: [
                        { required: true, message: '请选择项目', trigger: 'blur' },
                        // { validator: validateId, trigger: 'blur' }
                    ],
                    // id_project_admin: [
                    //     { required: true, message: '请选择负责人', trigger: 'blur' }
                    // ],
                    // id_depart: [
                    //     { required: true, message: '请选择部门', trigger: 'blur' }
                    // ]
                },
                agentlist: [],
                agentTotal: 0,
                departlist: [],
                projectlist: [],
                userlist: [],
                startSyncTime: 0,
                curPageAccount: 1,
                isAdmin: false,
                multipleSelection: [],
            }
        },
        mounted() {
            this.isAdmin = isAdmin(this.$store.state.user.id_role)   
            this.loadData()
        },
        methods: {
            loadData() {
                this.loadAccountList({})
                this.loadAgentList({})
                this.$store.dispatch('depart/list', this.loginform).then((e) => {
                    // console.log('customer 部门列表', e)
                    this.departlist = e
                })
                this.$axios.get('/project/list', {})
                .then(e => {
                    // let data = e.data
                    // console.log('customer 项目列表', e.data.items)
                    this.projectlist = e.data.items
                })
                this.$axios.get('/user/list', {})
                .then(e => {
                    // console.log('customer 人员列表', e)
                    this.userlist = e.data
                })
            },
            loadAccountList(param, callback) {
                param['number'] = this.pageSize
                if (this.account_search != '') {
                    param['keyword'] = this.account_search
                }
                if (this.config_search != '') {
                    param['is_set'] = this.config_search
                }
                if (!param['page']) {
                    param['page'] = 1
                }
                this.curPageAccount = param['page']
                // console.log(param, this.curPageAccount)
                this.fullscreenLoading = true
                this.$axios.get('/account/list', param)
                .then(e => {
                    this.fullscreenLoading = false
                    // console.log('广告账号列表', e.data)
                    if (callback) {
                        callback(e.data)
                    } else {
                        this.accountlist = e.data.items
                        this.accountTotal = e.data.total
                    }
                })
                .catch(() => {
                })
            },
            loadAgentList(param, callback) {
                param['number'] = this.pageSize
                this.fullscreenLoading = true
                this.$axios.get('/agent/list', param)
                .then(e => {
                    this.fullscreenLoading = false
                    // console.log('授权列表', e.data)
                    if (callback) {
                        callback(e.data)
                    } else {
                        this.agentlist = e.data.items
                        this.agentTotal = e.data.total
                    }
                })
                .catch(() => {
                })
            },
            handleCurrentChange(t, val) {
                if (t == 'account') {
                    this.curPageAccount = val
                    this.loadAccountList({page: val})
                } else if (t == 'agent') {
                    this.loadAgentList({page: val})
                }
            },
            showConfig(item) {
                this.configform.id = []
                if (item == null) {
                    //多选情况
                    console.log(this.multipleSelection)
                    if (this.multipleSelection.length <= 0) {
                        return
                    }
                    this.multipleSelection.forEach(item => {
                        this.configform.id.push(item.id)
                    })
                    this.configform.account = this.multipleSelection[0].account
                    if (this.multipleSelection.length > 1) {
                        this.configform.account += ' 等' + this.multipleSelection.length + '个账户'
                        this.configform.id_project = ''
                    } else {
                        this.configform.id_project = this.multipleSelection[0].id_project == 0 ? '' : this.multipleSelection[0].id_project
                    }
                    this.fenpei = true
                    return
                }
                if (item.id_project == 0) {
                    item.id_project = ''
                }
                //this.configform = item
                this.configform.id.push(item.id)
                this.configform.account = item.account
                this.configform.id_project = item.id_project
                this.fenpei = true
            },
            deleteAgent(item) {
                this.$confirm('此操作将删除该项, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.fullscreenLoading = true
                    this.$axios.get('/agent/delete', {id: item.id})
                    .then(e => {
                        this.fullscreenLoading = false
                        this.$message({
                            type: 'success',
                            message: e.msg ? e.msg : '删除成功!'
                        })
                        this.loadAgentList({})
                    })
                    .catch(() => {
                        this.fullscreenLoading = false
                    })
                }).catch(() => {
                });
            },
            authClick() {
                window.open(ToutiaoAuthUrl, '_blank')
                // this.$router.push()
            },
            syncAccount() {
                if (this.startSyncTime === 0) {
                    this.startSyncTime = (new Date()).getTime() / 1000
                }
                this.syncloading = true
                this.$axios.get('/account/sync', {time: this.startSyncTime})
                .then(e => {
                    if (e.data.status == '1') {
                        this.syncloading = false
                        this.startSyncTime = 0
                        this.$message({
                            type: 'success',
                            message: e.msg ? e.msg : '同步成功!'
                        })
                        this.loadAgentList({page: this.curPageAccount})
                    } else {
                        setTimeout(() => {
                            this.syncAccount()
                        }, 2000);
                    }
                })
                .catch(() => {
                    this.syncloading = false
                })
            },
            syncClick() {
                this.$confirm('此操作比较耗时, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.syncAccount()
                }).catch(() => {
                })
            },
            exportClick() {
                location.href = 'api/account/export?token=' + getToken()
                // window.open('api/account/export?token=' + getToken(), '_blank')
                // this.$message({
                //     type: 'success',
                //     message: '暂未实现!'
                // })
            },
            configPost() {
                this.$refs['configform'].validate((valid) => {
                    if (valid) {
                        this.fenpei = false
                        this.fullscreenLoading = true
                        // console.log('this.configform', this.configform)
                        // let postData = {id: this.configform.id, id_depart: this.configform.id, id_project: this.configform.id_project, id_project_admin: this.configform.id_project_admin}
                        let postData = {id: this.configform.id, id_project: this.configform.id_project}
                        this.$axios.post('/account/config', postData)
                        .then(e => {
                            // this.$refs['addUserForm'].resetFields()
                            this.fullscreenLoading = false
                            this.$message.success(e.msg ? e.msg : '操作成功')
                            // console.log('添加结果', e)
                            this.loadAccountList({page: this.curPageAccount})
                        })
                        .catch(() => {
                            this.fullscreenLoading = false
                        })
                    } else {
                        console.log('error submit!!')
                        return false
                    }
                })
            },
            cancelConfig() {
                this.fenpei = false
                this.$refs['configform'].resetFields()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row)
                    });
                } else {
                    this.$refs.multipleTable.clearSelection()
                }
            },
        }
    }
</script>
